package com.jin.webvideo.base.util;

public class TokenBucket {
    // 令牌产生速率  ms/个
    private int frequency;
    // 桶大小
    private long bucketSize;
    // 可用数量
    private long tokenCount;
    // 上次访问时间
    private long time;

    public void setBucketSize(long bucketSize) {
        this.bucketSize = bucketSize;
    }

    public void setFrequency(int frequency) {
        this.frequency = frequency;
    }

    public void setTokenCount(long tokenCount) {
        this.tokenCount = tokenCount;
    }

    public synchronized boolean allow() {
        long now = System.currentTimeMillis();
        long count = (now - time) / frequency;
        if (count > 0) {
            time = now;
        }
        if (tokenCount < 0) {
            tokenCount = 0;
        }
        tokenCount += count;
        if (tokenCount > bucketSize) {
            tokenCount = bucketSize;
        }
        tokenCount --;
        return tokenCount < 0;
    }

    public TokenBucket copy() {
        TokenBucket tokenBucket = new TokenBucket();
        tokenBucket.bucketSize = bucketSize;
        tokenBucket.tokenCount = tokenCount;
        tokenBucket.frequency = frequency;
        return tokenBucket;
    }
}
